package com.gx.auth.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gx.auth.dao.FunctionInterfaceDAO;
import com.gx.auth.entity.Function;
import com.gx.auth.entity.User;

public class FunctionInterfaceImplDAO implements FunctionInterfaceDAO{
	private   Connection conn = null;
	
	public  FunctionInterfaceImplDAO(Connection conn) {
		this.conn = conn  ;
	}

	@Override
	public int insert(Function t) throws SQLException {
		String sql = "insert into auth_function (f_name,url,createtime,updatetime) values (?,?,datetime('now', 'localtime'),datetime('now', 'localtime')) ";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getFname());
		pst.setString(2, t.getUrl());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int delete(Function t) throws SQLException {
		String sql = "delete from auth_function where f_name = ? ";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getFname());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int update(Function t) throws SQLException {
		String sql = "update  auth_function set url=?,updatetime=datetime('now', 'localtime')  where f_name = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getUrl());
		pst.setString(2, t.getFname());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public List<Function> queryAll() throws SQLException {
		List<Function> ls = new ArrayList<>();
		String sql = "select * from auth_function ";
		PreparedStatement pst = conn.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		while (rs.next()) {
			ls.add(saveResult(rs));
		}
		rs.close();
		pst.close();
		return ls;
	}


	@Override
	public List<Function>  query(User u) throws SQLException {
		List<Function> ls = new ArrayList<>();
		String sql = "select * from auth_function where f_id in (select f_id from auth_role_function where r_id in (select r_id from auth_user_role where u_id in (select u_id from auth_user where u_name = ?)) )";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, u.getUname());
		ResultSet rs = pst.executeQuery();
		while (rs.next()) {
			ls.add(saveResult(rs));
		}
		rs.close();
		pst.close();
		return ls;
	}

	@Override
	public Function saveResult(ResultSet rs) throws SQLException {
		Function fc = new Function();
		fc.setFid(rs.getInt("f_id"));
		fc.setFname(rs.getString("f_name"));
		fc.setUrl(rs.getString("url"));
		fc.setCreatetime(rs.getString("createtime"));
		fc.setUpdatetime(rs.getString("updatetime"));
		return fc;
	}
	
	

}
